package com.dny.asmtop.op;

import com.dny.asmtop.ASMMethodUtils;
import com.dny.asmtop.Command;
import com.dny.asmtop.MethodContext;
import jdk.internal.org.objectweb.asm.Type;

import java.util.Objects;

/**
 * Created by jlutt on 2018-01-16.
 * 定义临时变量
 * @author jlutt
 */
public class CommandLet implements Variable {

  private final Command field;
  private VarLocal var;

  public CommandLet(Command field) {
    this.field = field;
  }

  @Override
  public Type type(MethodContext context) {
    return field.type(context);
  }

  @Override
  public Type generator(MethodContext context) {
    if (var == null) {
      var = ASMMethodUtils.newLocal(context, field.type(context));
      field.generator(context);
      var.store(context);
    }
    var.generator(context);
    return field.type(context);
  }

  @Override
  public Object beginStore(MethodContext context) {
    return null;
  }

  @Override
  public void store(MethodContext context, Object storeContext, Type type) {
    if (var == null) {
      var = ASMMethodUtils.newLocal(context, field.type(context));
      field.generator(context);
      var.store(context);
    }

    var.store(context, storeContext, type);
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    CommandLet that = (CommandLet) o;
    return Objects.equals(field, that.field);
  }

  @Override
  public int hashCode() {
    return Objects.hash(field);
  }
}
